from flask import current_app
from flask import g, jsonify
from flask import request
from info import constants, db
from info.models import News, Category, User
from info.modules import news
from info.response_code import RET
from info.utils.commons import user_login_data
from info.utils.image_storage import image_storage
from . import profile_blue
from flask import render_template


# 其他用户界面
# 请求路径: /user/other
# 请求方式: GET
# 请求参数:id
# 返回值: 渲染other.html页面,字典data数据
@profile_blue.route('/other')
@user_login_data
def other():
    # 1.获取参数
    author_id = request.args.get("id")

    # 2.参数校验(为空校验)
    if not author_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 3.通过id查找关注对象是否存在
    try:
        users = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="获取id失败")

    if not users:
        return jsonify(errno=RET.DATAERR, errmsg="该关注对象不存在")

    # 4.判断用户是否关注过该作者
    is_followed = False
    # 4.1判断用户是否登陆
    if g.user:
        # 用户在作者的粉丝列表里
        if g.user in users.followers.all():
            is_followed = True
    # print(users.followers)

    # 5.携带参数渲染页面
    data = {
        "authors": users.to_dict(),
        "is_followed": is_followed
    }
    return render_template("news/other.html", data=data)

# # 功能描述: 获取作者详情
# # 请求路径: /user/other
# # 请求方式: GET
# # 请求参数:id
# # 返回值: 渲染other.html页面,字典data数据
# @profile_blue.route('/other')
# @user_login_data
# def other():
#     # 1.获取参数
#     author_id = request.args.get("id")
#
#     # 2.校验为空校验
#     if not author_id:
#         return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
#
#     # 3.根据编号取出作者对象,判断作者对象是否存在
#     try:
#         author = User.query.get(author_id)
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DBERR, errmsg="获取作者失败")
#
#     if not author: return jsonify(errno=RET.NODATA, errmsg="作者不存在")
#
#     # 3.1 判断该用户是否,关注过该新闻的作者
#     is_followed = False
#     if g.user:
#         if g.user in author.followers:
#             is_followed = True
#
#     # 4.携带作者数据,渲染页面
#     data = {
#         "author": author.to_dict(),
#         "user_info": g.user.to_dict() if g.user else "",
#         "is_followed": is_followed
#     }
#     return render_template("news/other.html", data=data)

# 获取我的关注
# 请求路径: /user/user_follow
# 请求方式: GET
# 请求参数:p
# 返回值: 渲染user_follow.html页面,字典data数据
@profile_blue.route('/user_follow')
@user_login_data
def user_follow():
    # 1.获取参数
    page = request.args.get("p", "1")

    # 2.参数类型转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    # 3.分页查询我的关注
    try:
        paginate = g.user.followed.paginate(page, 2, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取失败")

    # 4.获取分页属性,总页数,当前页,当前页属性
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 5.把数据转换成字典
    user_list = []
    for item in items:
        user_list.append(item.to_dict())

    # 6.携带参数,渲染页面
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "authors": user_list
    }
    return render_template("news/user_follow.html", data=data)


# 用户新闻列表
# 请求路径: /user/news_list
# 请求方式:GET
# 请求参数:p
# 返回值:GET渲染user_news_list.html页面
@profile_blue.route('/news_list')
@user_login_data
def news_list():
    # 1.获取参数
    page = request.args.get("p", "1")

    # 2.参数类型转换
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)

    # 3.分页查询用户发布的新闻
    try:
        paginate=News.query.filter(News.user_id == g.user.id).order_by(News.create_time.desc()).paginate(page, 2, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="获取新闻失败")

    # 4.获取分页属性,总页数,当前页数,当前页数属性
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 5.把新闻列表转换成字典
    news_list = []
    for item in items:
        news_list.append(item.to_review_dict())

    # 6.携带数据渲染页面
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "news_items": news_list
    }
    return render_template("news/user_news_list.html", data=data)


# 获取/设置,新闻发布
# 请求路径: /user/news_release
# 请求方式:GET,POST
# 请求参数:GET无, POST ,title, category_id,digest,index_image,content
# 返回值:GET请求,user_news_release.html, data分类列表字段数据, POST,errno,errmsg
@profile_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    # 1.判断请求方式是否为GET
    if request.method == "GET":

        # 1.1查询分类数据
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errnp=RET.DBERR, errmsg="获取数据失败")

        categories_list = []
        for category in categories:
            categories_list.append(category.to_dict())

        # 1.2携带数据渲染页面
        return render_template("news/user_news_release.html", categories=categories_list)

    # 2.如果请求方式为POST
    # 2.1获取参数
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")

    # 2.2校验参数(为空校验)
    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 2.3上传图像
    try:
        image_name = image_storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="图片获取失败")

    if not image_name: return jsonify(errno=RET.NODATA, errmsg="图片上传失败")

    # 2.4创建新闻对象,设置新闻属性
    news = News()
    news.title = title
    news.source = g.user.nick_name
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.category_id = category_id
    news.user_id = g.user.id
    news.status = 1

    # 2.5保存新闻到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, reemsg="输入信息错误")

    # 2.6返回响应
    return jsonify(errno=RET.OK, errmsg="成功")


# 获取新闻收藏列表
# 请求路径: /user/collection
# 请求方式:GET
# 请求参数:p(页数)
# 返回值: user_collection.html页面
@profile_blue.route('/collection')
@user_login_data
def collection():
    # 1.获取参数
    page = request.args.get("p", "1")

    # 2.参数类型转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    # 3.分页查询，每页5条
    try:
        paginate = g.user.collection_news.order_by(News.create_time.desc()).paginate(page, 5, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻获取失败")

    # 4.取出分页对象属性,总页数,当前页,当前页对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 4.1将对象转换成字典
    news_list = []
    for item in items:
        news_list.append(item.to_dict())

    # 5.拼接数据,渲染页面
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "abc": news_list
    }
    return render_template("news/user_collection.html", data=data)


# 获取/设置,用户头像上传
# 请求路径: /user/pic_info
# 请求方式:GET,POST
# 请求参数:无, POST有参数,avatar
# 返回值:GET请求: user_pci_info.html页面,data字典数据, POST请求: errno, errmsg,avatar_url
@profile_blue.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    # 1.判断请求方式是否为get
    if request.method == "GET":
        return render_template("news/user_pic_info.html", user=g.user.to_dict())

    # 2.如果请求方式是POST
    # 2.1获取参数
    avatar = request.files.get("avatar")

    # 2.2校验参数(为空校验)
    if not avatar:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 2.3上传图片,并判断图片是否上传成功
    try:
        image_name = image_storage(avatar.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云上传异常")
    if not image_name:
        return jsonify(errno=RET.DATAERR, errmsg="图片上传失败")

    # 2.4给用户设置头像属性
    try:
        g.user.avatar_url = image_name
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="设置失败")

    # 2.5返回响应
    data = {
        "avatar_url": constants.QINIU_DOMIN_PREFIX + image_name
    }
    return jsonify(errno=RET.OK, errmsg="成功", data=data)


# 获取/设置用户密码
# 请求路径: /user/pass_info
# 请求方式:GET,POST
# 请求参数:GET无, POST有参数,old_password, new_password
# 返回值:GET请求: user_pass_info.html页面 , POST请求: errno, errmsg
@profile_blue.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():

    # 1.判断请求方式是否是GET
    if request.method == "GET":
        return render_template("news/user_pass_info.html")

    # 2.如果不是GET
    # 2.1获取参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    # 2.2校验参数(为空校验)
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 2.3判断旧密码是否正确
    if not g.user.check_password(old_password):
        return jsonify(errno=RET.DATAERR, errmsg="旧密码输入错误")

    # 2.4判断旧密码和新密码是否一致
    if old_password == new_password:
        return jsonify(errno=RET.DATAERR, errmsg="新旧密码一致")

    # 2.5设置新密码
    try:
        g.user.password = new_password
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="设置密码错误")

    # 2.6返回响应体
    return jsonify(errno=RET.OK, errmsg="成功")


# 获取 / 设置用户基本信息
# 请求路径: / user / base_info
# 请求方式: GET, POST
# 请求参数: POST请求有参数, nick_name, signature, gender
# 返回值: errno, errmsg
@profile_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():

    # 1.判断是否是GET请求
    if request.method == "GET":
        return render_template("news/user_base_info.html", user=g.user.to_dict())

    # 2.如果是POST请求
    # 2.1获取参数
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    # 2.2校验参数(为空校验)
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 2.3判断性别类型是否符合常理
    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.DBERR, errmsg="性别参数获取错误")

    # 2.4修改用户数据
    try:
        g.user.nick_name = nick_name
        g.user.gender = gender
        g.user.signature = signature
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="修改数据失败")

    # 2.5返回响应体
    return jsonify(errno=RET.OK, errmsg="成功")


# 获取用户信息首页
# 请求路径: /user/info
# 请求方式:GET
# 请求参数:无
# 返回值: user.html页面,用户字典data数据
@profile_blue.route('/info')
@user_login_data
def profile_info():

    # 判断用户是否有登陆
    if not g.user:
        return render_template("/")

    # 拼接数据渲染页面
    data = {
        "user_info": g.user.to_dict()
    }

    return render_template("news/user.html", data=data)
